package com.smasher.nfc.protocol.ndef

import android.annotation.SuppressLint
import android.nfc.NdefMessage
import android.nfc.NdefRecord
import android.nfc.Tag
import android.nfc.tech.Ndef
import android.nfc.tech.TagTechnology
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import java.lang.ref.WeakReference
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class NdefHelper(val callback: (Boolean, String) -> Unit) {

    private val executorService: ExecutorService = Executors.newSingleThreadExecutor()

    private fun closeTagTechnology(technology: TagTechnology) {
        try {
            technology.close()
        } catch (e: Exception) {
            Log.e(TAG, "close tag technology: ", e)
        }
    }

    fun writeTag(tag: Tag, data: String) {
        val ndef = Ndef.get(tag)
        if (ndef != null) {
            executorService.execute {
                try {
                    ndef.connect()
                    ndef.use {
                        if (!it.isWritable) {
                            Log.d(TAG, "NDEF tag is not writable.")
                            handler2.sendMessage(Message.obtain().apply {
                                what = WHAT_WRITABLE
                            })
                            return@use
                        }

                        val ndefRecord = NdefRecord.createTextRecord(null, data)
                        val ndefMessage = NdefMessage(arrayOf(ndefRecord))
                        it.writeNdefMessage(ndefMessage)

                        // 发送成功消息给 Handler
                        handler2.sendMessage(Message.obtain().apply {
                            what = WHAT_WRITE_SUCCESS
                        })
                    }
                } catch (e: Exception) {
                    Log.e(
                        TAG,
                        "An unexpected error occurred while writing to the NFC tag.",
                        e
                    )
                } finally {
                    // 注意：由于 use 已经处理了关闭逻辑，这里不需要再显式地关闭 NDEF 连接
                }
            }
        }
    }

    @SuppressLint("HandlerLeak")
    private val handler2: Handler = object : Handler(Looper.getMainLooper()) {
        private val callbackRef: WeakReference<(Boolean, String) -> Unit> = WeakReference(callback)

        override fun handleMessage(msg: Message) {
            val callback = callbackRef.get() ?: return
            when (msg.what) {
                WHAT_WRITE_SUCCESS -> {
                    callback.invoke(true, "写入成功")
                }

                WHAT_WRITABLE -> {
                    callback.invoke(false, "NDEF不可写入")
                }

                else -> {}
            }
        }
    }

    companion object {
        const val WHAT_WRITE_SUCCESS = 1057
        const val WHAT_WRITABLE = 1056
        const val TAG = "Ndef"
    }
}